package comm

import (
	"bytes"
	"encoding/binary"
	"log"
)

const MSG_HEADER = "netfly"
const MSG_LEN_LEN = 4 // int32

var (
	Msg_header_len = len(MSG_HEADER)
)

func BytesToInt32(bData []byte) int {
	var nRet int32
	buffer := bytes.NewBuffer(bData[:4])
	binary.Read(buffer, binary.BigEndian, &nRet)
	return int(nRet)
}

func Int32ToBytes(nVal int) []byte {
	buffer := bytes.NewBuffer([]byte{})
	binary.Write(buffer, binary.BigEndian, int32(nVal))
	return buffer.Bytes()
}

func PackMsg(msg []byte) (bRet []byte) {
	if len(msg) <= 0 {
		log.Println("PackMsg, msg len is 0")
		return
	}
	bRet = append(bRet, []byte(MSG_HEADER)...)
	bRet = append(bRet, Int32ToBytes(len(msg))...)
	bRet = append(bRet, msg...)
	return
}

func UnPackMsg(bData *[]byte) (bRet []byte, ok bool) {
	ok = true
	nSrcLen := len(*bData)
	nFirst := bytes.Index(*bData, []byte(MSG_HEADER))
	if nFirst < 0 || nSrcLen <= (Msg_header_len+MSG_LEN_LEN) {
		ok = false
		return
	}
	nMsgLen := BytesToInt32((*bData)[nFirst+Msg_header_len : nFirst+Msg_header_len+MSG_LEN_LEN])
	if nMsgLen <= 0 {
		// fix len error bug
		*bData = (*bData)[nFirst+Msg_header_len+MSG_LEN_LEN:]
		//ok = false
		return
	}
	if nMsgLen > (nSrcLen - Msg_header_len - MSG_LEN_LEN - nFirst) {
		ok = false
		return
	}
	bRet = (*bData)[nFirst+Msg_header_len+MSG_LEN_LEN : nFirst+Msg_header_len+MSG_LEN_LEN+nMsgLen]
	*bData = (*bData)[nFirst+Msg_header_len+MSG_LEN_LEN+nMsgLen:]
	return
}
